package com.action.gulimall.product.exception;

import com.action.common.exception.BizCodeEnum;
import com.action.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName GlobalExceptionAdvice
 * @Deacription 统一异常返回
 * @Author sl
 * @Date 2021/6/15/015 12:05
 * @Version 1.0
 **/
@Slf4j
@RestControllerAdvice(basePackages = {"com.action.gulimall.product.controller"})
public class GlobalExceptionAdvice {

    /* * @Author sl
     * @Description 校验异常
     * @Date 12:06 2021/6/15/015
     **/
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public R handleValidException(MethodArgumentNotValidException ex){
        log.error("校验异常", ex);
        BindingResult bindingResult = ex.getBindingResult();
        Map<String,String> errMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError) -> {
            errMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMessage())
                .put("data",errMap);
    }

    /* * @Author sl
     * @Description 其他异常
     * @Date 12:06 2021/6/15/015
     **/
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        log.error("错误异常{}",throwable);
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMessage());
    }
}
